package com.wva.video.consumer.sync2es;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.wva.common.utils.CustomObjectMapper;
import com.wva.common.utils.JsonUtils;
import com.wva.es.utils.DataElasticsearchUtils;
import com.wva.video.domain.CanalMessageEntity;
import com.wva.video.domain.po.VideoMetadata;
import com.wva.video.service.VideoMetadataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 同步视频元信息到ES
 * @Author: hong
 * @Date: 2025/2/26 19:29:31
 */
@Component
@RabbitListener(queues = "video.canal.wva_video.video_metadata")
@Slf4j
public class VideoMetadataChangeConsumer {
    @Autowired
    DataElasticsearchUtils dataElasticsearchUtils;
    @Autowired
    VideoMetadataService videoMetadataService;

    JsonUtils jsonUtils;

    @RabbitHandler
    void handle(Message message, @Payload Object payload) throws JsonProcessingException {
        if (jsonUtils == null) {
            jsonUtils = new JsonUtils();
            jsonUtils.setObjectMapper(new CustomObjectMapper("yyyy-MM-dd HH:mm:ss"));
        }

        String messageString = new String(message.getBody(), StandardCharsets.UTF_8);
        CanalMessageEntity canalMessageEntity = jsonUtils.parse(messageString, CanalMessageEntity.class);

        List<Map<String, String>> data = canalMessageEntity.getData();
        List<Map<String, String>> old = canalMessageEntity.getOld();

        for (int i = 0; i < data.size(); i++) {
            if (old != null) {
                if (old.get(i) != null && !old.get(i).containsKey("duration")) continue;
            }

            VideoMetadata videoMetadata = jsonUtils.convertMap(data.get(i), VideoMetadata.class);
            dataElasticsearchUtils.update(
                    Collections.singletonMap("duration", videoMetadata.getDuration()),
                    String.valueOf(videoMetadata.getVideoId()),
                    "video"
            );
        }
    }


}
